import React, { useState, useEffect } from 'react'
import { useSelector } from 'react-redux'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useTranslation } from 'react-i18next'
import {
  UserIcon,
  CogIcon,
  BellIcon,
  ShieldCheckIcon,
  EyeIcon,
  EyeSlashIcon,
  DevicePhoneMobileIcon,
  ComputerDesktopIcon,
  SunIcon,
  MoonIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
  TrashIcon,
  ArrowRightOnRectangleIcon
} from '@heroicons/react/24/outline'
import { selectUser } from '@/store/slices/authSlice'
import { Card, Button, Input, Badge, ConfirmModal } from '@/components/ui'
import { ErrorBoundary } from '@/components/common'

// Form schemas
const profileSchema = z.object({
  displayName: z.string()
    .min(2, 'Display name must be at least 2 characters')
    .max(50, 'Display name must be less than 50 characters'),
  email: z.string().email('Invalid email address'),
  bio: z.string().max(500, 'Bio must be less than 500 characters').optional(),
  website: z.string().url('Invalid website URL').optional().or(z.literal('')),
  location: z.string().max(100, 'Location must be less than 100 characters').optional(),
  company: z.string().max(100, 'Company must be less than 100 characters').optional()
})

const passwordSchema = z.object({
  currentPassword: z.string().min(1, 'Current password is required'),
  newPassword: z.string()
    .min(8, 'Password must be at least 8 characters')
    .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, 'Password must contain at least one uppercase letter, one lowercase letter, and one number'),
  confirmPassword: z.string()
}).refine((data) => data.newPassword === data.confirmPassword, {
  message: "Passwords don't match",
  path: ["confirmPassword"],
})

const notificationSchema = z.object({
  emailNotifications: z.boolean(),
  pushNotifications: z.boolean(),
  marketingEmails: z.boolean(),
  securityAlerts: z.boolean(),
  pluginUpdates: z.boolean(),
  weeklyDigest: z.boolean()
})

type ProfileFormData = z.infer<typeof profileSchema>
type PasswordFormData = z.infer<typeof passwordSchema>
type NotificationFormData = z.infer<typeof notificationSchema>

interface UserSettings {
  theme: 'light' | 'dark' | 'system'
  language: string
  timezone: string
  dateFormat: string
  itemsPerPage: number
  autoSave: boolean
  compactMode: boolean
}

export const DeveloperSettingsPage: React.FC = () => {
  const { t, i18n } = useTranslation()
  // const dispatch = useDispatch<AppDispatch>()
  const user = useSelector(selectUser)

  const [activeTab, setActiveTab] = useState<'profile' | 'security' | 'notifications' | 'preferences' | 'danger'>('profile')
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  const [showCurrentPassword, setShowCurrentPassword] = useState(false)
  const [showNewPassword, setShowNewPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)

  // Modal states
  const [deleteAccountModalOpen, setDeleteAccountModalOpen] = useState(false)
  const [logoutAllModalOpen, setLogoutAllModalOpen] = useState(false)

  // Settings state
  const [settings, setSettings] = useState<UserSettings>({
    theme: 'system',
    language: i18n.language,
    timezone: 'UTC',
    dateFormat: 'MM/dd/yyyy',
    itemsPerPage: 20,
    autoSave: true,
    compactMode: false
  })

  // Form instances
  const profileForm = useForm<ProfileFormData>({
    resolver: zodResolver(profileSchema),
    defaultValues: {
      displayName: user?.displayName || '',
      email: user?.email || '',
      bio: '',
      website: '',
      location: '',
      company: ''
    }
  })

  const passwordForm = useForm<PasswordFormData>({
    resolver: zodResolver(passwordSchema)
  })

  const notificationForm = useForm<NotificationFormData>({
    resolver: zodResolver(notificationSchema),
    defaultValues: {
      emailNotifications: true,
      pushNotifications: true,
      marketingEmails: false,
      securityAlerts: true,
      pluginUpdates: true,
      weeklyDigest: false
    }
  })

  useEffect(() => {
    // Load user settings
    // In a real app, this would fetch from API
  }, [])

  const handleProfileSubmit = async (data: ProfileFormData) => {
    setIsLoading(true)
    setError(null)
    setSuccess(null)

    try {
      // Mock API call - replace with actual API call
      await new Promise(resolve => setTimeout(resolve, 1000))
      console.log('Profile data:', data)
      setSuccess('Profile updated successfully')
    } catch (error: any) {
      setError(error.message || 'Failed to update profile')
    } finally {
      setIsLoading(false)
    }
  }

  const handlePasswordSubmit = async (data: PasswordFormData) => {
    setIsLoading(true)
    setError(null)
    setSuccess(null)

    try {
      // API call to change password
      console.log('Password data:', data)
      await new Promise(resolve => setTimeout(resolve, 1000)) // Mock API call
      setSuccess('Password changed successfully')
      passwordForm.reset()
    } catch (error: any) {
      setError(error.message || 'Failed to change password')
    } finally {
      setIsLoading(false)
    }
  }

  const handleNotificationSubmit = async (data: NotificationFormData) => {
    setIsLoading(true)
    setError(null)
    setSuccess(null)

    try {
      // API call to update notification preferences
      console.log('Notification data:', data)
      await new Promise(resolve => setTimeout(resolve, 1000)) // Mock API call
      setSuccess('Notification preferences updated')
    } catch (error: any) {
      setError(error.message || 'Failed to update notification preferences')
    } finally {
      setIsLoading(false)
    }
  }

  const handleDeleteAccount = async () => {
    setIsLoading(true)
    try {
      // Mock API call - replace with actual API call
      await new Promise(resolve => setTimeout(resolve, 1000))
      console.log('Account deletion requested')
      // Redirect will be handled by the auth slice
    } catch (error: any) {
      setError(error.message || 'Failed to delete account')
    } finally {
      setIsLoading(false)
      setDeleteAccountModalOpen(false)
    }
  }

  const handleLogoutAllDevices = async () => {
    setIsLoading(true)
    try {
      // API call to logout from all devices
      await new Promise(resolve => setTimeout(resolve, 1000)) // Mock API call
      setSuccess('Logged out from all devices successfully')
    } catch (error: any) {
      setError(error.message || 'Failed to logout from all devices')
    } finally {
      setIsLoading(false)
      setLogoutAllModalOpen(false)
    }
  }

  const tabs = [
    { id: 'profile', name: t('settings.tabs.profile'), icon: UserIcon },
    { id: 'security', name: t('settings.tabs.security'), icon: ShieldCheckIcon },
    { id: 'notifications', name: t('settings.tabs.notifications'), icon: BellIcon },
    { id: 'preferences', name: t('settings.tabs.preferences'), icon: CogIcon },
    { id: 'danger', name: t('settings.tabs.dangerZone'), icon: ExclamationTriangleIcon }
  ]

  const clearMessages = () => {
    setError(null)
    setSuccess(null)
  }

  return (
    <ErrorBoundary>
      <div className="space-y-6">
        {/* Header */}
        <div>
          <h1 className="text-2xl font-bold text-gray-900">{t('settings.title')}</h1>
          <p className="text-gray-600 mt-1">
            {t('settings.subtitle')}
          </p>
        </div>

        {/* Global Messages */}
        {error && (
          <div className="flex items-center p-4 bg-red-50 border border-red-200 rounded-md">
            <ExclamationTriangleIcon className="h-5 w-5 text-red-400 mr-3" />
            <div className="text-sm text-red-700">{error}</div>
            <button
              onClick={clearMessages}
              className="ml-auto text-red-400 hover:text-red-600"
            >
              ×
            </button>
          </div>
        )}

        {success && (
          <div className="flex items-center p-4 bg-green-50 border border-green-200 rounded-md">
            <CheckCircleIcon className="h-5 w-5 text-green-400 mr-3" />
            <div className="text-sm text-green-700">{success}</div>
            <button
              onClick={clearMessages}
              className="ml-auto text-green-400 hover:text-green-600"
            >
              ×
            </button>
          </div>
        )}

        <div className="flex flex-col lg:flex-row gap-6">
          {/* Sidebar Navigation */}
          <div className="lg:w-64 flex-shrink-0">
            <Card className="p-4">
              <nav className="space-y-1">
                {tabs.map((tab) => {
                  const Icon = tab.icon
                  return (
                    <button
                      key={tab.id}
                      onClick={() => setActiveTab(tab.id as any)}
                      className={`w-full flex items-center px-3 py-2 text-sm font-medium rounded-md transition-colors ${
                        activeTab === tab.id
                          ? 'bg-primary-100 text-primary-700 border-primary-200'
                          : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                      }`}
                    >
                      <Icon className="h-5 w-5 mr-3" />
                      {tab.name}
                    </button>
                  )
                })}
              </nav>
            </Card>
          </div>

          {/* Main Content */}
          <div className="flex-1">
            {activeTab === 'profile' && (
              <Card className="p-6">
                <div className="mb-6">
                  <h2 className="text-lg font-medium text-gray-900 mb-2">{t('settings.profile.title')}</h2>
                  <p className="text-sm text-gray-600">
                    {t('settings.profile.description')}
                  </p>
                </div>

                <form onSubmit={profileForm.handleSubmit(handleProfileSubmit)} className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <Input
                      label={t('settings.profile.displayName')}
                      placeholder={t('settings.profile.displayNamePlaceholder')}
                      error={profileForm.formState.errors.displayName?.message}
                      {...profileForm.register('displayName')}
                      fullWidth
                    />

                    <Input
                      label={t('settings.profile.email')}
                      type="email"
                      placeholder={t('settings.profile.emailPlaceholder')}
                      error={profileForm.formState.errors.email?.message}
                      {...profileForm.register('email')}
                      fullWidth
                    />

                    <Input
                      label={t('settings.profile.website')}
                      placeholder={t('settings.profile.websitePlaceholder')}
                      error={profileForm.formState.errors.website?.message}
                      {...profileForm.register('website')}
                      fullWidth
                    />

                    <Input
                      label={t('settings.profile.location')}
                      placeholder={t('settings.profile.locationPlaceholder')}
                      error={profileForm.formState.errors.location?.message}
                      {...profileForm.register('location')}
                      fullWidth
                    />

                    <Input
                      label={t('settings.profile.company')}
                      placeholder={t('settings.profile.companyPlaceholder')}
                      error={profileForm.formState.errors.company?.message}
                      {...profileForm.register('company')}
                      fullWidth
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Bio
                    </label>
                    <textarea
                      {...profileForm.register('bio')}
                      rows={4}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500"
                      placeholder="Tell us about yourself..."
                    />
                    {profileForm.formState.errors.bio && (
                      <p className="mt-1 text-sm text-red-600">
                        {profileForm.formState.errors.bio.message}
                      </p>
                    )}
                  </div>

                  <div className="flex justify-end">
                    <Button
                      type="submit"
                      loading={isLoading}
                      disabled={isLoading}
                    >
                      Save Changes
                    </Button>
                  </div>
                </form>
              </Card>
            )}

            {activeTab === 'security' && (
              <div className="space-y-6">
                {/* Change Password */}
                <Card className="p-6">
                  <div className="mb-6">
                    <h2 className="text-lg font-medium text-gray-900 mb-2">{t('settings.security.changePassword')}</h2>
                    <p className="text-sm text-gray-600">
                      {t('settings.security.changePasswordDescription')}
                    </p>
                  </div>

                  <form onSubmit={passwordForm.handleSubmit(handlePasswordSubmit)} className="space-y-6">
                    <Input
                      label={t('settings.security.currentPassword')}
                      type={showCurrentPassword ? 'text' : 'password'}
                      placeholder={t('settings.security.currentPasswordPlaceholder')}
                      error={passwordForm.formState.errors.currentPassword?.message}
                      rightIcon={
                        <button
                          type="button"
                          onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                          className="text-gray-400 hover:text-gray-600"
                        >
                          {showCurrentPassword ? <EyeSlashIcon className="h-5 w-5" /> : <EyeIcon className="h-5 w-5" />}
                        </button>
                      }
                      {...passwordForm.register('currentPassword')}
                      fullWidth
                    />

                    <Input
                      label={t('settings.security.newPassword')}
                      type={showNewPassword ? 'text' : 'password'}
                      placeholder={t('settings.security.newPasswordPlaceholder')}
                      error={passwordForm.formState.errors.newPassword?.message}
                      rightIcon={
                        <button
                          type="button"
                          onClick={() => setShowNewPassword(!showNewPassword)}
                          className="text-gray-400 hover:text-gray-600"
                        >
                          {showNewPassword ? <EyeSlashIcon className="h-5 w-5" /> : <EyeIcon className="h-5 w-5" />}
                        </button>
                      }
                      {...passwordForm.register('newPassword')}
                      fullWidth
                    />

                    <Input
                      label={t('settings.security.confirmPassword')}
                      type={showConfirmPassword ? 'text' : 'password'}
                      placeholder={t('settings.security.confirmPasswordPlaceholder')}
                      error={passwordForm.formState.errors.confirmPassword?.message}
                      rightIcon={
                        <button
                          type="button"
                          onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                          className="text-gray-400 hover:text-gray-600"
                        >
                          {showConfirmPassword ? <EyeSlashIcon className="h-5 w-5" /> : <EyeIcon className="h-5 w-5" />}
                        </button>
                      }
                      {...passwordForm.register('confirmPassword')}
                      fullWidth
                    />

                    <div className="flex justify-end">
                      <Button
                        type="submit"
                        loading={isLoading}
                        disabled={isLoading}
                      >
                        {t('settings.security.updatePassword')}
                      </Button>
                    </div>
                  </form>
                </Card>

                {/* Two-Factor Authentication */}
                <Card className="p-6">
                  <div className="mb-6">
                    <h2 className="text-lg font-medium text-gray-900 mb-2">{t('settings.security.twoFactorAuth')}</h2>
                    <p className="text-sm text-gray-600">
                      {t('settings.security.twoFactorAuthDescription')}
                    </p>
                  </div>

                  <div className="flex items-center justify-between p-4 bg-gray-50 rounded-md">
                    <div className="flex items-center">
                      <ShieldCheckIcon className="h-8 w-8 text-gray-400 mr-3" />
                      <div>
                        <p className="text-sm font-medium text-gray-900">{t('settings.security.twoFactorAuth')}</p>
                        <p className="text-sm text-gray-600">{t('settings.security.notEnabled')}</p>
                      </div>
                    </div>
                    <Button variant="outline">
                      {t('settings.security.enable2FA')}
                    </Button>
                  </div>
                </Card>

                {/* Active Sessions */}
                <Card className="p-6">
                  <div className="mb-6">
                    <h2 className="text-lg font-medium text-gray-900 mb-2">Active Sessions</h2>
                    <p className="text-sm text-gray-600">
                      Manage and log out your active sessions on other browsers and devices.
                    </p>
                  </div>

                  <div className="space-y-4">
                    <div className="flex items-center justify-between p-4 border rounded-md">
                      <div className="flex items-center">
                        <ComputerDesktopIcon className="h-8 w-8 text-gray-400 mr-3" />
                        <div>
                          <p className="text-sm font-medium text-gray-900">Current Session</p>
                          <p className="text-sm text-gray-600">Chrome on macOS • Last active now</p>
                        </div>
                      </div>
                      <Badge variant="success">Current</Badge>
                    </div>

                    <div className="flex items-center justify-between p-4 border rounded-md">
                      <div className="flex items-center">
                        <DevicePhoneMobileIcon className="h-8 w-8 text-gray-400 mr-3" />
                        <div>
                          <p className="text-sm font-medium text-gray-900">Mobile Device</p>
                          <p className="text-sm text-gray-600">Safari on iOS • Last active 2 hours ago</p>
                        </div>
                      </div>
                      <Button size="sm" variant="outline">
                        Revoke
                      </Button>
                    </div>
                  </div>

                  <div className="mt-6 pt-6 border-t">
                    <Button
                      variant="outline"
                      onClick={() => setLogoutAllModalOpen(true)}
                      icon={<ArrowRightOnRectangleIcon />}
                    >
                      Log Out All Other Sessions
                    </Button>
                  </div>
                </Card>
              </div>
            )}

            {activeTab === 'notifications' && (
              <Card className="p-6">
                <div className="mb-6">
                  <h2 className="text-lg font-medium text-gray-900 mb-2">{t('settings.notifications.title')}</h2>
                  <p className="text-sm text-gray-600">
                    {t('settings.notifications.description')}
                  </p>
                </div>

                <form onSubmit={notificationForm.handleSubmit(handleNotificationSubmit)} className="space-y-6">
                  <div className="space-y-4">
                    <div className="flex items-center justify-between">
                      <div>
                        <label className="text-sm font-medium text-gray-900">{t('settings.notifications.email')}</label>
                        <p className="text-sm text-gray-600">{t('settings.notifications.emailDescription')}</p>
                      </div>
                      <input
                        type="checkbox"
                        {...notificationForm.register('emailNotifications')}
                        className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
                      />
                    </div>

                    <div className="flex items-center justify-between">
                      <div>
                        <label className="text-sm font-medium text-gray-900">{t('settings.notifications.push')}</label>
                        <p className="text-sm text-gray-600">{t('settings.notifications.pushDescription')}</p>
                      </div>
                      <input
                        type="checkbox"
                        {...notificationForm.register('pushNotifications')}
                        className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
                      />
                    </div>

                    <div className="flex items-center justify-between">
                      <div>
                        <label className="text-sm font-medium text-gray-900">{t('settings.notifications.security')}</label>
                        <p className="text-sm text-gray-600">{t('settings.notifications.securityDescription')}</p>
                      </div>
                      <input
                        type="checkbox"
                        {...notificationForm.register('securityAlerts')}
                        className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
                      />
                    </div>

                    <div className="flex items-center justify-between">
                      <div>
                        <label className="text-sm font-medium text-gray-900">{t('settings.notifications.pluginUpdates')}</label>
                        <p className="text-sm text-gray-600">{t('settings.notifications.pluginUpdatesDescription')}</p>
                      </div>
                      <input
                        type="checkbox"
                        {...notificationForm.register('pluginUpdates')}
                        className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
                      />
                    </div>

                    <div className="flex items-center justify-between">
                      <div>
                        <label className="text-sm font-medium text-gray-900">{t('settings.notifications.marketing')}</label>
                        <p className="text-sm text-gray-600">{t('settings.notifications.marketingDescription')}</p>
                      </div>
                      <input
                        type="checkbox"
                        {...notificationForm.register('marketingEmails')}
                        className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
                      />
                    </div>

                    <div className="flex items-center justify-between">
                      <div>
                        <label className="text-sm font-medium text-gray-900">{t('settings.notifications.weeklyDigest')}</label>
                        <p className="text-sm text-gray-600">{t('settings.notifications.weeklyDigestDescription')}</p>
                      </div>
                      <input
                        type="checkbox"
                        {...notificationForm.register('weeklyDigest')}
                        className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
                      />
                    </div>
                  </div>

                  <div className="flex justify-end">
                    <Button
                      type="submit"
                      loading={isLoading}
                      disabled={isLoading}
                    >
                      {t('settings.notifications.savePreferences')}
                    </Button>
                  </div>
                </form>
              </Card>
            )}

            {activeTab === 'preferences' && (
              <div className="space-y-6">
                {/* Appearance */}
                <Card className="p-6">
                  <div className="mb-6">
                    <h2 className="text-lg font-medium text-gray-900 mb-2">{t('settings.appearance.title')}</h2>
                    <p className="text-sm text-gray-600">
                      {t('settings.appearance.description')}
                    </p>
                  </div>

                  <div className="space-y-6">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-3">{t('settings.appearance.theme')}</label>
                      <div className="grid grid-cols-3 gap-3">
                        {[
                          { value: 'light', labelKey: 'settings.appearance.light', icon: SunIcon },
                          { value: 'dark', labelKey: 'settings.appearance.dark', icon: MoonIcon },
                          { value: 'system', labelKey: 'settings.appearance.system', icon: ComputerDesktopIcon }
                        ].map((theme) => {
                          const Icon = theme.icon
                          return (
                            <button
                              key={theme.value}
                              onClick={() => setSettings(prev => ({ ...prev, theme: theme.value as any }))}
                              className={`p-4 border rounded-lg flex flex-col items-center space-y-2 transition-colors ${
                                settings.theme === theme.value
                                  ? 'border-primary-500 bg-primary-50'
                                  : 'border-gray-300 hover:border-gray-400'
                              }`}
                            >
                              <Icon className="h-6 w-6" />
                              <span className="text-sm font-medium">{t(theme.labelKey)}</span>
                            </button>
                          )
                        })}
                      </div>
                    </div>

                    <div className="flex items-center justify-between">
                      <div>
                        <label className="text-sm font-medium text-gray-900">{t('settings.appearance.compactMode')}</label>
                        <p className="text-sm text-gray-600">{t('settings.appearance.compactModeDescription')}</p>
                      </div>
                      <input
                        type="checkbox"
                        checked={settings.compactMode}
                        onChange={(e) => setSettings(prev => ({ ...prev, compactMode: e.target.checked }))}
                        className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
                      />
                    </div>
                  </div>
                </Card>

                {/* Localization */}
                <Card className="p-6">
                  <div className="mb-6">
                    <h2 className="text-lg font-medium text-gray-900 mb-2">Localization</h2>
                    <p className="text-sm text-gray-600">
                      Set your language, timezone, and date format preferences.
                    </p>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">Language</label>
                      <select
                        value={settings.language}
                        onChange={(e) => {
                          const newLanguage = e.target.value
                          setSettings(prev => ({ ...prev, language: newLanguage }))
                          i18n.changeLanguage(newLanguage)
                        }}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500"
                      >
                        <option value="en">English</option>
                        <option value="zh">中文</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">Timezone</label>
                      <select
                        value={settings.timezone}
                        onChange={(e) => setSettings(prev => ({ ...prev, timezone: e.target.value }))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500"
                      >
                        <option value="UTC">UTC</option>
                        <option value="America/New_York">Eastern Time</option>
                        <option value="America/Los_Angeles">Pacific Time</option>
                        <option value="Europe/London">London</option>
                        <option value="Asia/Tokyo">Tokyo</option>
                        <option value="Asia/Shanghai">Shanghai</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">Date Format</label>
                      <select
                        value={settings.dateFormat}
                        onChange={(e) => setSettings(prev => ({ ...prev, dateFormat: e.target.value }))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500"
                      >
                        <option value="MM/dd/yyyy">MM/dd/yyyy</option>
                        <option value="dd/MM/yyyy">dd/MM/yyyy</option>
                        <option value="yyyy-MM-dd">yyyy-MM-dd</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">Items per page</label>
                      <select
                        value={settings.itemsPerPage}
                        onChange={(e) => setSettings(prev => ({ ...prev, itemsPerPage: parseInt(e.target.value) }))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500"
                      >
                        <option value={10}>10</option>
                        <option value={20}>20</option>
                        <option value={50}>50</option>
                        <option value={100}>100</option>
                      </select>
                    </div>
                  </div>

                  <div className="mt-6 flex items-center justify-between">
                    <div>
                      <label className="text-sm font-medium text-gray-900">Auto-save</label>
                      <p className="text-sm text-gray-600">Automatically save your work</p>
                    </div>
                    <input
                      type="checkbox"
                      checked={settings.autoSave}
                      onChange={(e) => setSettings(prev => ({ ...prev, autoSave: e.target.checked }))}
                      className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
                    />
                  </div>

                  <div className="mt-6 flex justify-end">
                    <Button>
                      Save Preferences
                    </Button>
                  </div>
                </Card>
              </div>
            )}

            {activeTab === 'danger' && (
              <Card className="p-6 border-red-200">
                <div className="mb-6">
                  <h2 className="text-lg font-medium text-red-900 mb-2">{t('settings.danger.title')}</h2>
                  <p className="text-sm text-red-600">
                    {t('settings.danger.description')}
                  </p>
                </div>

                <div className="space-y-6">
                  <div className="p-4 border border-red-200 rounded-md bg-red-50">
                    <div className="flex items-center justify-between">
                      <div>
                        <h3 className="text-sm font-medium text-red-900">{t('settings.danger.logoutAllDevices')}</h3>
                        <p className="text-sm text-red-600">
                          {t('settings.danger.logoutAllDevicesDescription')}
                        </p>
                      </div>
                      <Button
                        variant="danger"
                        onClick={() => setLogoutAllModalOpen(true)}
                        icon={<ArrowRightOnRectangleIcon />}
                      >
                        {t('settings.danger.logoutAll')}
                      </Button>
                    </div>
                  </div>

                  <div className="p-4 border border-red-200 rounded-md bg-red-50">
                    <div className="flex items-center justify-between">
                      <div>
                        <h3 className="text-sm font-medium text-red-900">{t('settings.danger.deleteAccount')}</h3>
                        <p className="text-sm text-red-600">
                          {t('settings.danger.deleteAccountDescription')}
                        </p>
                      </div>
                      <Button
                        variant="danger"
                        onClick={() => setDeleteAccountModalOpen(true)}
                        icon={<TrashIcon />}
                      >
                        {t('settings.danger.deleteAccount')}
                      </Button>
                    </div>
                  </div>
                </div>
              </Card>
            )}
          </div>
        </div>

        {/* Modals */}
        <ConfirmModal
          isOpen={deleteAccountModalOpen}
          onClose={() => setDeleteAccountModalOpen(false)}
          onConfirm={handleDeleteAccount}
          title={t('settings.danger.deleteAccount')}
          message={t('settings.danger.deleteAccountConfirmMessage')}
          confirmText={t('settings.danger.deleteAccount')}
          variant="danger"
        />

        <ConfirmModal
          isOpen={logoutAllModalOpen}
          onClose={() => setLogoutAllModalOpen(false)}
          onConfirm={handleLogoutAllDevices}
          title={t('settings.danger.logoutAllDevices')}
          message={t('settings.danger.logoutAllConfirmMessage')}
          confirmText={t('settings.danger.logoutAll')}
          variant="danger"
        />
      </div>
    </ErrorBoundary>
  )
}
